package com.ruoyi.wms.service.impl;

import java.util.*;

import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.MD5Utils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.wms.dto.WarehouseDto;
import com.ruoyi.wms.vo.TreeVo;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.wms.mapper.WarehouseMapper;
import com.ruoyi.wms.domain.Warehouse;
import com.ruoyi.wms.service.IWarehouseService;

/**
 * 仓库Service业务层处理
 *
 * @author ruoyi
 * @date 2025-10-20
 */
@Service
public class WarehouseServiceImpl implements IWarehouseService {
    @Autowired
    private WarehouseMapper warehouseMapper;

    /**
     * 查询仓库
     *
     * @param id 仓库主键
     * @return 仓库
     */
    @Override
    public Warehouse selectWarehouseById(String id) {
        return warehouseMapper.selectWarehouseById(id);
    }

    /**
     * 查询仓库列表
     *
     * @param warehouse 仓库
     * @return 仓库
     */
    @Override
    public List<Warehouse> selectWarehouseList(WarehouseDto warehouse) {
        return warehouseMapper.selectWarehouseList(warehouse);
    }

    /**
     * 新增仓库
     *
     * @param warehouse 仓库
     * @return 结果
     */
    @Override
    public int insertWarehouse(Warehouse warehouse) {
        warehouse.setCreateDate(DateUtils.getCurrentTime());

        warehouse.setId(MD5Utils.md5(warehouse.getWarehouseCode()));
        warehouse.setCreateUser(SecurityUtils.getUsername());
        warehouse.setCreateDate(DateUtils.getCurrentTime());
        warehouse.setUpdateDate(DateUtils.getCurrentTime());

        return warehouseMapper.insertWarehouse(warehouse);
    }

    /**
     * 修改仓库
     *
     * @param warehouse 仓库
     * @return 结果
     */
    @Override
    public int updateWarehouse(Warehouse warehouse) {

        int updateResult = 0;
        if (StringUtils.isEmpty(warehouse.getId())) {
            updateResult = insertWarehouse(warehouse);
        }
        warehouse.setUpdateDate(DateUtils.getCurrentTime());
        updateResult = warehouseMapper.updateWarehouse(warehouse);
        if (0 == updateResult) {
            updateResult = insertWarehouse(warehouse);
        }

        return updateResult;


    }

    /**
     * 批量删除仓库
     *
     * @param ids 需要删除的仓库主键
     * @return 结果
     */
    @Override
    public int deleteWarehouseByIds(String[] ids) {
        return warehouseMapper.deleteWarehouseByIds(ids);
    }

    /**
     * 删除仓库信息
     *
     * @param id 仓库主键
     * @return 结果
     */
    @Override
    public int deleteWarehouseById(String id) {
        return warehouseMapper.deleteWarehouseById(id);
    }

    @Override
    public List<TreeVo> buildWarehouseTree() {
        // 1. 获取原始数据
        List<Map<String, Object>> rawDataList = warehouseMapper.selectAllWarehouses();

        // 2. 构建树形结构
        List<TreeVo> tree = buildTreeStructure(rawDataList);

        // 3. 打印树形结构（调试用）
        printTree(tree, 0);

        return tree;
    }

    @Override
    public List<Map<String, Object>> getWarehouseList() {
        return warehouseMapper.selectAllWarehouses();
    }

    /**
     * 构建树形结构
     */
    private List<TreeVo> buildTreeStructure(List<Map<String, Object>> rawDataList) {
        if (CollectionUtils.isEmpty(rawDataList)) {
            return new ArrayList<>();
        }

        Map<String, TreeVo> warehouseMap = new HashMap<>();
        List<TreeVo> rootNodes = new ArrayList<>();

        for (Map<String, Object> row : rawDataList) {
            String warehouseName = getStringValue(row, "warehouse_name");
            String warehouseCode = getStringValue(row, "warehouse_code");

            String areaCode = getStringValue(row, "id2");
            String areaName = getStringValue(row, "area_name");
            String areaNo = getStringValue(row, "area_code");

            // 处理仓库节点
            if (!warehouseMap.containsKey(warehouseCode)) {
                TreeVo warehouseNode = createWarehouseNode(warehouseCode, warehouseName, warehouseCode);
                warehouseMap.put(warehouseCode, warehouseNode);
                rootNodes.add(warehouseNode);
            }

            // 处理库区节点
            if (isValidAreaData(areaCode, areaName, areaNo)) {
                TreeVo areaNode = createAreaNode(areaCode, areaName, areaNo, warehouseCode);
                TreeVo warehouseNode = warehouseMap.get(warehouseCode);
                if (warehouseNode.getChildren() == null) {
                    warehouseNode.setChildren(new ArrayList<>());
                }
                warehouseNode.getChildren().add(areaNode);
            }
        }

        // 对树进行排序
        sortTreeNodes(rootNodes);

        return rootNodes;
    }

    /**
     * 打印树形结构
     */
    private void printTree(List<TreeVo> tree, int level) {
        for (TreeVo node : tree) {
            StringBuilder indent = new StringBuilder();
            for (int i = 0; i < level; i++) {
                indent.append("  ");
            }
//            log.debug("{}{} [{}] {}", indent, node.getLevel(), node.getCode(), node.getName());
            if (!CollectionUtils.isEmpty(node.getChildren())) {
                printTree(node.getChildren(), level + 1);
            }
        }
    }

    // 其他辅助方法保持不变...
    private TreeVo createWarehouseNode(String id, String name, String code) {
        TreeVo node = new TreeVo();
        node.setId(id);
        node.setName(name);
        node.setCode(code);
        node.setLevel("warehouse");
        node.setParentId(null);
        node.setChildren(new ArrayList<>());
        return node;
    }

    private TreeVo createAreaNode(String id, String name, String code, String parentId) {
        TreeVo node = new TreeVo();
        node.setId(id);
        node.setName(name);
        node.setCode(code);
        node.setLevel("area");
        node.setParentId(parentId);
        node.setChildren(new ArrayList<>());
        return node;
    }

    private boolean isValidAreaData(String areaCode, String areaName, String areaNo) {
        return areaCode != null && !areaCode.isEmpty() &&
                areaName != null && !areaName.isEmpty() &&
                areaNo != null && !areaNo.isEmpty() &&
                !"null".equals(areaCode) && !"null".equals(areaName) && !"null".equals(areaNo);
    }

    private String getStringValue(Map<String, Object> map, String key) {
        Object value = map.get(key);
        return value != null ? String.valueOf(value) : null;
    }

    private void sortTreeNodes(List<TreeVo> nodes) {
        if (CollectionUtils.isEmpty(nodes)) {
            return;
        }

        nodes.sort(Comparator.comparing(TreeVo::getCode, Comparator.nullsLast(String::compareTo)));

        for (TreeVo node : nodes) {
            if (!CollectionUtils.isEmpty(node.getChildren())) {
                node.getChildren().sort(Comparator.comparing(TreeVo::getCode, Comparator.nullsLast(String::compareTo)));
            }
        }
    }
}


